package com.banciyuan.bcywebview.biz.pc.zone.smooth;

import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.myinterface.PushActionInterface;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.dialog.WaitDialog;
import com.banciyuan.bcywebview.base.view.foldview.FoldLayout;
import com.banciyuan.bcywebview.base.view.imageview.CircleImageView;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.textview.FocusButton;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.ask.AskActivity;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.follow.FollowingActivity;
import com.banciyuan.bcywebview.biz.main.discover.topcreator.TopCreatorActivity;
import com.banciyuan.bcywebview.biz.pc.EditInfoActivity;
import com.banciyuan.bcywebview.biz.pc.PersonHelper;
import com.banciyuan.bcywebview.biz.privatemessage.EditPrivateMessageActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.soundcloud.android.crop.Crop;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.MineInfo;
import de.greenrobot.daoexample.model.PrivateMessage;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.UserDetail;

/**
 * Created by squall on 2016/10/8.
 */

public class SmoothPersonActivity extends BaseActivity implements View.OnClickListener, FoldLayout.OnFoldScrollListener, BaseWatcher {

    public final static String UNFOLLOW = "unfollow";
    public final static String EACHFOLLOW = "eachfollow";
    public final static int REQ_PIC = 1;
    public final static int GO_EDIT = 2;

    private View mProgressbarView;
    private MyProgressDialog mProgressDialog;
    private ProgressbarHelper mProgressbarHelper;

    private ViewPager mPager;
    private FoldLayout mFoldLayout;
    private TabLayout mTabLayout;
    private LinearLayout ll_header;
    private TextView followed_num;
    private TextView following_num;
    private TextView getzan_num;

    private CircleImageView head_img;
    private ImageView gender_img;
    private TextView name_tv;
    private TextView roles_tv;
    private TextView focus_iv;
    private TextView edit_iv;
    private TextView friend_iv;
    private TextView focued_iv;
    private ImageView back;
    private ImageView vip_logo;
    private RelativeLayout gouda_ll;
    private RelativeLayout huiying_ll;
    private View left_block;
    private TextView person_name;
    private TextView focus_btn;
    private View viewAnsweredNum;
    private TextView tvAnsweredNum;
    private ImageView privateMessage;
    private ImageView iv_more;
    private RelativeLayout rlBottom;
    private View contral_btn;

    private PersonHelper mHeadHelper;
    private PushActionInterface mChangeHeadImageInterface;


    public String uid = "";
    private RequestQueue queue;

    private UserDetail user;

    public boolean isNeedFouce = false;
    public boolean headShow = true;
    public boolean isRlBottomShowing = true;
    public boolean isBottomAnimRunning = false;

    private SmoothPersonFragment personFragment;
    private SmoothPersonTimeLineFragment middleFragment;
    private SmoothPersonTimeLineFragment rightFragment;
    private List<Fragment> flist = new ArrayList<>();
    private String[] tabs;

    private WaitDialog waitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersive();
        setContentView(R.layout.activity_smooth_person);
        initArgs();
        getFragment();
        initProgressbar();
        initUi();
        setAdatper();
        initAction();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(SmoothPersonActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(SmoothPersonActivity.class);
    }

    private void getFragment() {
        Bundle origin = new Bundle();
        origin.putString("uid", uid);
        origin.putString("filter", "origin");

        Bundle tuijian = new Bundle();
        tuijian.putString("uid", uid);
        tuijian.putString("filter", "tuijian");

        Bundle userBundle = new Bundle();
        userBundle.putString("uid", uid);

        middleFragment = new SmoothPersonTimeLineFragment();
        middleFragment.passParentScrollY(this);
        middleFragment.setArguments(origin);

        personFragment = new SmoothPersonFragment();
        personFragment.passParentScrollY(this);
        personFragment.setArguments(userBundle);

        rightFragment = new SmoothPersonTimeLineFragment();
        rightFragment.passParentScrollY(this);
        rightFragment.setArguments(tuijian);

        flist.add(personFragment);
        flist.add(middleFragment);
        flist.add(rightFragment);
    }

    private void setAdatper() {
        mPager.setOffscreenPageLimit(3);
        mPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return flist.get(position);
            }

            @Override
            public int getCount() {
                return flist.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return tabs[position];
            }
        });
        mTabLayout.setupWithViewPager(mPager);
        mPager.setCurrentItem(1);
        StatService.onEvent(SmoothPersonActivity.this, EventConstants.PERSON_POST, EventConstants.PERSON_POST);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        if (TextUtils.isEmpty(uid)) uid = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        queue = VolleyQueue.getRquest(SmoothPersonActivity.this);
        mChangeHeadImageInterface = new PushActionInterface() {
            @Override
            public void onNetError(String result) {
                if (mProgressDialog != null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
                MyToast.show(SmoothPersonActivity.this, getString(R.string.failtouploadavatar));
            }

            @Override
            public void PushSuccess(String result) {
                if (mProgressDialog != null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
                UserDataHelper.getInstance(SmoothPersonActivity.this).setAvatar(result);
                BaseObserver.getInstance().notifyWatchers(BaseObserver.USER_DATA_CHANGE_EVENT);
                initData();
            }
        };
        mHeadHelper = new PersonHelper(SmoothPersonActivity.this, mChangeHeadImageInterface);
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mHeadHelper.cancelAll();
                mProgressDialog.dismiss();
            }
        };
        onCancelClick = new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                mHeadHelper.cancelAll();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(SmoothPersonActivity.this);
        mProgressDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).setCancelTxt(getString(R.string.cancel_update)).create();

        if (StringUtil.notNullEqual(uid, UserDataHelper.getInstance(SmoothPersonActivity.this).getUid())) {
            tabs = new String[]{getString(R.string.about_me), getString(R.string.post), getString(R.string.recommend_unit)};
        } else {
            tabs = new String[]{getString(R.string.about_others), getString(R.string.post), getString(R.string.recommend_unit)};
        }

    }

    @Override
    protected void initUi() {
        waitDialog = new WaitDialog(this, R.style.Dialog);
        following_num = (TextView) findViewById(R.id.person_care_tv);
        followed_num = (TextView) findViewById(R.id.person_fans_tv);
        getzan_num = (TextView) findViewById(R.id.getzan_tv);
        head_img = (CircleImageView) findViewById(R.id.person_head_img);
        gender_img = (ImageView) findViewById(R.id.iv_gender);
        name_tv = (TextView) findViewById(R.id.person_name_tv);
        roles_tv = (TextView) findViewById(R.id.tv_role);
        focus_iv = (TextView) findViewById(R.id.iv_attention);
        focued_iv = (TextView) findViewById(R.id.iv_attentioned);
        friend_iv = (TextView) findViewById(R.id.iv_attention_eachother);
        edit_iv = (TextView) findViewById(R.id.iv_edit_material);
        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        gouda_ll = (RelativeLayout) findViewById(R.id.rl_gouda);
        huiying_ll = (RelativeLayout) findViewById(R.id.rl_huiying);
        mPager = (ViewPager) findViewById(R.id.person_viewpager);
        ll_header = (LinearLayout) findViewById(R.id.person_head);
        rlBottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        left_block = findViewById(R.id.left_block);
        person_name = (TextView) findViewById(R.id.base_action_bar_title);
        focus_btn = (TextView) findViewById(R.id.focus_btn);
        back = (ImageView) findViewById(R.id.base_action_bar_home);
        viewAnsweredNum = findViewById(R.id.rl_answered_num);
        tvAnsweredNum = (TextView) findViewById(R.id.tv_answered_num);
        vip_logo = (ImageView) findViewById(R.id.vip_logo);
        privateMessage = (ImageView) findViewById(R.id.private_message_btn);
        iv_more = (ImageView) findViewById(R.id.iv_more);
        mFoldLayout = (FoldLayout) findViewById(R.id.fold_header);
        contral_btn = findViewById(R.id.rl_profile);

        findViewById(R.id.rl_guanzhu).setOnClickListener(this);
        findViewById(R.id.rl_fans).setOnClickListener(this);

        if (StringUtil.notNullEqual(uid, UserDataHelper.getInstance(SmoothPersonActivity.this).getUid())) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                iv_more.setImageDrawable(getResources().getDrawable(R.drawable.more_writer, getTheme()));
            } else {
                iv_more.setImageDrawable(getResources().getDrawable(R.drawable.more_writer));
            }
            huiying_ll.setVisibility(View.VISIBLE);
            gouda_ll.setVisibility(View.GONE);
            iv_more.setOnClickListener(this);
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                iv_more.setImageDrawable(getResources().getDrawable(R.drawable.more, getTheme()));
            } else {
                iv_more.setImageDrawable(getResources().getDrawable(R.drawable.more));
            }
            huiying_ll.setVisibility(View.GONE);
            gouda_ll.setVisibility(View.VISIBLE);
            iv_more.setOnClickListener(this);
        }
    }

    protected void initData() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, SmoothPersonActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject result = jsonObject.getJSONObject("data");
                        Gson gson = new Gson();
                        user = gson.fromJson(result.toString(), new TypeToken<UserDetail>() {
                        }.getType());
                        personDataSuccess();
                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                    }
                } else {
                    mProgressbarHelper.onFailed();
                }

            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
            }
        };
        CommonApiUtils.getPersonDataBigHead(SmoothPersonActivity.this, queue, onSuccess, onError, uid);
    }

    public void personDataSuccess() {
        privateMessage.setVisibility(View.VISIBLE);
        if (user.isValue_user()) {
            vip_logo.setVisibility(View.VISIBLE);
        } else {
            vip_logo.setVisibility(View.GONE);
        }
        if (user.getSex() == 0) {
            gender_img.setImageResource(R.drawable.profile_girl);
        } else {
            gender_img.setImageResource(R.drawable.profile_boy);
        }
        if (StringUtil.notNullStartWithUrlHead(user.getAvatar())) {
            ImageLoader.getInstance().displayImage(user.getAvatar(), head_img, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
                    new AsyncTask<Void, Bitmap, Bitmap>() {

                        @Override
                        protected Bitmap doInBackground(Void... params) {
                            try {
                                return ImageManager.fastblur(ThumbnailUtils.extractThumbnail(loadedImage, 200, 200), 20);
                            } catch (Exception e) {
                                return null;
                            }
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            if (bitmap != null) {
                                ((ImageView) findViewById(R.id.person_bg)).setImageBitmap(bitmap);
                            }
                        }
                    }.execute();
                }
            });
        }
        if (!TextUtils.isEmpty(user.getUname())) {
            name_tv.setText(user.getUname());
            person_name.setText(user.getUname());
        }
        final ViewTreeObserver observer = name_tv.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (name_tv.getLineCount() > 1) {
                    name_tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                }
                if (observer.isAlive()) {
                    observer.removeOnPreDrawListener(this);
                }
                return true;
            }
        });
        followed_num.setText(String.valueOf(user.getFollower()));
        following_num.setText(String.valueOf(user.getFollowing()));
        getzan_num.setText(String.valueOf(user.getDing_count()));
        int unAnswered = user.getUnasked();
        String answeredCount = user.getAnswer_count();
        if (StringUtil.notNullEqual(uid, UserDataHelper.getInstance(SmoothPersonActivity.this).getUid())) {
            if (unAnswered > 0) {
                FlagUtils.newAskNum = unAnswered;
            }
            edit_iv.setVisibility(View.VISIBLE);
            privateMessage.setVisibility(View.GONE);
        } else {
            if (StringUtil.notNullEqual(user.getFollowstate(), UNFOLLOW)) {
                isNeedFouce = true;
                setUnFollow();
            } else if (StringUtil.notNullEqual(user.getFollowstate(), EACHFOLLOW)) {
                setEachFollow();
            } else {
                setFollow();
            }
            if (TextUtils.isEmpty(answeredCount) || "0".equals(answeredCount)) {
                viewAnsweredNum.setVisibility(View.GONE);
            } else {
                viewAnsweredNum.setVisibility(View.VISIBLE);
                tvAnsweredNum.setText(answeredCount);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < user.getRoles().size(); i++) {
            String type_name = user.getRoles().get(i).getType_name();
            if (StringUtil.notNullEqual(type_name, UserDataHelper.DRAWER_ROLE)) {
                sb.append(getString(R.string.draw_role) + " / ");
            } else if (StringUtil.notNullEqual(type_name, UserDataHelper.WRITE_ROLE)) {
                sb.append(getString(R.string.write_role) + " / ");
            } else if (StringUtil.notNullEqual(type_name, UserDataHelper.COSER_ROLE)) {
                sb.append(getString(R.string.coser_role) + " / ");
            }
        }
        if (!TextUtils.isEmpty(sb.toString())) {
            sb.delete(sb.length() - 3, sb.length());
        }
        roles_tv.setText(sb.toString());
        if (personFragment != null) {
            personFragment.setSelf(user);
        }
    }

    private void setUnFollow() {
        if (focus_iv != null) {
            focus_iv.setVisibility(View.VISIBLE);
            focued_iv.setVisibility(View.GONE);
            friend_iv.setVisibility(View.GONE);
        }
        isNeedFouce = true;
        if (!headShow) {
            focus_btn.setVisibility(View.VISIBLE);
        }

    }

    private void setEachFollow() {
        if (focus_iv != null) {
            focus_iv.setVisibility(View.GONE);
            focued_iv.setVisibility(View.GONE);
            friend_iv.setVisibility(View.VISIBLE);
        }
        isNeedFouce = false;
        if (!headShow) {
            focus_btn.setVisibility(View.GONE);
        }
    }

    private void setFollow() {
        if (focus_iv != null) {
            focus_iv.setVisibility(View.GONE);
            focued_iv.setVisibility(View.VISIBLE);
            friend_iv.setVisibility(View.GONE);
        }
        isNeedFouce = false;
        if (!headShow) {
            focus_btn.setVisibility(View.GONE);
        }
    }

    private void getMoreInterestUser() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.FID, uid));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, SmoothPersonActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<MineInfo> users = gson.fromJson(jsonObject.getString("data"), new TypeToken<List<MineInfo>>() {
                        }.getType());
                        processMoreUsers(users);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                }

            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
            }
        };

        StringRequestParam getFrontRequest = new StringRequestParam(Request.Method.POST, HttpUtils.BASE_URL +
                UserApi.getRecommendMore(), params, onSuccess, onError);
        queue.add(getFrontRequest);
    }

    private void processMoreUsers(List<MineInfo> users) {
        if (users.size() == 0)
            return;

        View popView = View.inflate(this, R.layout.recommend_user_layout, null);

        ImageView[] userAvatars = new ImageView[]{(ImageView) popView.findViewById(R.id.user_head_one),
                (ImageView) popView.findViewById(R.id.user_head_two), (ImageView) popView.findViewById(R.id.user_head_three)};
        TextView[] userNames = new TextView[]{(TextView) popView.findViewById(R.id.recommend_user_name_one),
                (TextView) popView.findViewById(R.id.recommend_user_name_two), (TextView) popView.findViewById(R.id.recommend_user_name_three)};

        TextView[] userIntros = new TextView[]{(TextView) popView.findViewById(R.id.intro_one),
                (TextView) popView.findViewById(R.id.intro_two), (TextView) popView.findViewById(R.id.intro_three)};
        TagView[] userRoles = new TagView[]{(TagView) popView.findViewById(R.id.roles_line_one),
                (TagView) popView.findViewById(R.id.roles_line_two), (TagView) popView.findViewById(R.id.roles_line_three)};

        View[] viewUserContainers = new View[]{popView.findViewById(R.id.viewcontainer_user_one),
                popView.findViewById(R.id.viewcontainer_user_two), popView.findViewById(R.id.viewcontainer_user_three)};

        FocusButton[] focusButtons = new FocusButton[]{(FocusButton) popView.findViewById(R.id.focus_btn_one),
                (FocusButton) popView.findViewById(R.id.focus_btn_two), (FocusButton) popView.findViewById(R.id.focus_btn_three)};
        int length = users.size() > 3 ? 3 : users.size();
        removeIlleaglView(viewUserContainers, length);
        for (int i = 0; i < length; i++) {
            final MineInfo moreUser = users.get(i);
            ImageLoader.getInstance().displayImage(moreUser.getAvatar(), userAvatars[i], ImageOptions.optionHead);
            userNames[i].setText(moreUser.getUname());
            userIntros[i].setText(moreUser.getReason());
            List<TagDetail> tagDetails = new ArrayList<>();
            int tagLength = moreUser.getRoles().size() > 2 ? 2 : moreUser.getRoles().size();
            for (int j = 0; j < tagLength; j++) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setTag_name(moreUser.getRoles().get(j).getType_name());
                tagDetails.add(tagDetail);
            }
            userRoles[i].setTlist(tagDetails);
            userNames[i].setMaxWidth(CommonUtils.getWidthPixels(this) - UIUtils.dip2px(155, this) - tagLength * UIUtils.dip2px(36, this));
            viewUserContainers[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gotoUtil.gotoAct(SmoothPersonActivity.this, SmoothPersonActivity.class, moreUser.getUid());
                }
            });
            final FocusButton focusButton = focusButtons[i];
            focusButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    doMoreUserFollow(focusButton, moreUser);
                }
            });
        }
        popView.findViewById(R.id.view_find_more_users).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(SmoothPersonActivity.this, TopCreatorActivity.class);
            }
        });

        final PopupWindow popupWindow = new PopupWindow(popView, -1, -1, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.showAtLocation(head_img, Gravity.TOP, 0, 0);
        popView.findViewById(R.id.user_container).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFinishing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    private void removeIlleaglView(View[] viewUserContainers, int length) {
        if (length < 3) {
            for (int i = 2; i >= length; i--) {
                viewUserContainers[i].setVisibility(View.GONE);
            }
        }
    }

    private void doMoreUserFollow(final FocusButton focusButton, final MineInfo user) {
        final String type = "unfollow".equals(user.getFollow_state()) ? "dofollow" : "unfollow";
        if ("unfollow".equals(type)) {
            ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
            builder.setDescString(getString(R.string.comfirm_unfollow_people))
                    .setActionString(getString(R.string.mydialog_comfirm))
                    .setCancelString(getString(R.string.mydialog_cancel))
                    .setActionClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            doMoreUserFollow(focusButton, user, type);
                        }
                    }).create().show();
        } else {
            doMoreUserFollow(focusButton, user, type);
        }
    }

    private void doMoreUserFollow(final FocusButton focusButton, final MineInfo user, final String type) {
        TimelineLikeHelper.doFollow(SmoothPersonActivity.this, type, user.getUid(), new TimelineLikeHelper.FollowSuccess() {
            @Override
            public void onFollowSuccess(String response) {
                try {
                    String newFollowState = type.equals("dofollow") ? "havefollow" : "unfollow";
                    user.setFollow_state(newFollowState);
                    focusButton.setSelected("havefollow".equals(newFollowState));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void dofollow() {
        doFollow("dofollow");
    }

    private void doCancel() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.comfirm_unfollow_people))
                .setActionString(getString(R.string.mydialog_comfirm))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doFollow("unfollow");
                    }
                }).create().show();
    }

    private void doFollow(String type) {
        final boolean flag = !type.equals("dofollow");
        TimelineLikeHelper.doFollow(this, type, uid, new TimelineLikeHelper.FollowSuccess() {
            @Override
            public void onFollowSuccess(String response) {
                try {
                    JSONObject result = new JSONObject(response);
                    String status = result.getString(HttpUtils.UPLOAD_STATUS);
                    if ("1".equals(status)) {
                        String content = result.getString(HttpUtils.UPLOAD_DATA);
                        if (flag) {
                            if ("01".equals(content)) {
                                setUnFollow();
                            }
                        } else {
                            if ("11".equals(content) || "12".equals(content)) {
                                setFollow();
                            }
                            if ("13".equals(content)) {
                                setEachFollow();
                            }
                            getMoreInterestUser();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    protected void initAction() {
        mFoldLayout.setOnFoldComplate(new FoldLayout.OnFoldComplate() {
            @Override
            public void folded() {
                headShow = false;
                if (isNeedFouce) {
                    focus_btn.setVisibility(View.VISIBLE);
                }
                left_block.setVisibility(View.VISIBLE);
                person_name.setVisibility(View.VISIBLE);
                contral_btn.setVisibility(View.GONE);
                hideBottom();
            }

            @Override
            public void unfolder() {
                headShow = true;
                focus_btn.setVisibility(View.GONE);
                left_block.setVisibility(View.GONE);
                person_name.setVisibility(View.GONE);
                contral_btn.setVisibility(View.VISIBLE);
                showBottom();
            }

            @Override
            public void folding(float percent, int height) {
                ll_header.setAlpha(1 - percent);
                findViewById(R.id.person_bg).setTranslationY(height / 2);
            }
        });

        focued_iv.setOnClickListener(this);
        focus_iv.setOnClickListener(this);
        friend_iv.setOnClickListener(this);
        edit_iv.setOnClickListener(this);
        back.setOnClickListener(this);
        head_img.setOnClickListener(this);
        gouda_ll.setOnClickListener(this);
        huiying_ll.setOnClickListener(this);
        focus_btn.setOnClickListener(this);
        ((View) (privateMessage.getParent())).setOnClickListener(this);

        mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                switch (tab.getPosition()) {
                    case 0:
                        StatService.onEvent(SmoothPersonActivity.this, EventConstants.PERSON_INTRO, EventConstants.PERSON_INTRO);
                        break;
                    case 1:
                        StatService.onEvent(SmoothPersonActivity.this, EventConstants.PERSON_POST, EventConstants.PERSON_POST);
                        break;
                    case 2:
                        StatService.onEvent(SmoothPersonActivity.this, EventConstants.PERSON_RECOMMEND, EventConstants.PERSON_RECOMMEND);
                        break;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (user == null) return;
        switch (v.getId()) {
            case R.id.private_message_btn_p:
                PrivateMessage privateMessage = new PrivateMessage();
                privateMessage.setUid(user.getUid());
                privateMessage.setUname(user.getUname());
                gotoUtil.gotoAct(SmoothPersonActivity.this, EditPrivateMessageActivity.class, privateMessage, "new");
                overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.rl_gouda:
            case R.id.rl_huiying:
                gotoUtil.gotoAct(SmoothPersonActivity.this, AskActivity.class, uid, user.getUname());
                break;
            case R.id.iv_attention:
            case R.id.focus_btn:
                dofollow();
                break;
            case R.id.iv_attentioned:
            case R.id.iv_attention_eachother:
                doCancel();
                break;
            case R.id.person_head_img:
                showHeadImage();
                break;
            case R.id.iv_edit_material:
                Intent intent = new Intent(SmoothPersonActivity.this, EditInfoActivity.class);
                intent.putExtra("avatar", user.getAvatar());
                intent.putExtra("name", user.getUname());
                intent.putExtra("address", user.getLocation());
                intent.putExtra("gender", String.valueOf(user.getSex()));
                intent.putExtra("selfIntro", user.getSelf_intro());
                startActivityForResult(intent, GO_EDIT);
                break;
            case R.id.base_action_bar_home:
                finish();
                break;
            case R.id.rl_guanzhu:
                intent = new Intent(SmoothPersonActivity.this, FollowingActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "following");
                intent.putExtra(gotoUtil.INTENT_VALUE_THREE, user.getUname() + getString(R.string.unit_focus_mount));
                startActivity(intent);
                break;
            case R.id.rl_fans:
                intent = new Intent(SmoothPersonActivity.this, FollowingActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "follower");
                intent.putExtra(gotoUtil.INTENT_VALUE_THREE, user.getUname() + getString(R.string.unit_fans_mount));
                startActivity(intent);
                break;
            case R.id.iv_more:
                goshare();
                break;
        }
    }

    private void showHeadImage() {
        View contentView = View.inflate(SmoothPersonActivity.this, R.layout.pop_show_headpic, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, -1, -1, true);
        final ImageView ivHead = (ImageView) contentView.findViewById(R.id.iv_head);
        final ProgressBar pb = (ProgressBar) contentView.findViewById(R.id.pb);
        if (null != user && null != user.getAvatar_fat()) {
            if (StringUtil.notNullStartWithUrlHead(user.getAvatar_fat())) {
                ImageLoader.getInstance().loadImage(user.getAvatar_fat(), ImageOptions.optionHead, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        ivHead.setImageBitmap(loadedImage);
                        pb.setVisibility(View.GONE);
                    }
                });
            } else {
                ivHead.setImageResource(R.drawable.user_pic_big);
                pb.setVisibility(View.GONE);
            }
        } else {
            ivHead.setImageResource(R.drawable.user_pic_big);
            pb.setVisibility(View.GONE);
        }
        TextView changeHead = (TextView) contentView.findViewById(R.id.tv_changehead);

        if (UserDataHelper.ifLogin(SmoothPersonActivity.this) && StringUtil.notNullEqual(UserDataHelper.getInstance(SmoothPersonActivity.this).getUid(), uid)) {
            changeHead.setVisibility(View.VISIBLE);
            changeHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                doChangeHeadImage();
                            }
                        }, 200);
                    }
                }
            });
        } else {
            changeHead.setVisibility(View.GONE);
        }
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(head_img, Gravity.TOP, 0, 0);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    public void showBottom() {
        if (null == rlBottom && !isBottomAnimRunning && isRlBottomShowing)
            return;
        ObjectAnimator.ofFloat(rlBottom, "translationY", 0)
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = true;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    public void hideBottom() {
        if (null == rlBottom && !isBottomAnimRunning && !isRlBottomShowing) return;
        ObjectAnimator.ofFloat(rlBottom, "translationY", UIUtils.dip2px(68, SmoothPersonActivity.this))
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = false;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    private void doChangeHeadImage() {
        Intent intent = new Intent(this, PhotoActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, true);
        startActivityForResult(intent, REQ_PIC);
    }


    private void goshare() {
        Intent intent = new Intent(SmoothPersonActivity.this, ShareActivity.class);
        if (!StringUtil.notNullEqual(uid, UserDataHelper.getInstance(SmoothPersonActivity.this).getUid())) {
            intent.putExtra("showblock", true);
            intent.putExtra("showPrivate", true);
            intent.putExtra("showWarnBtn", true);
        } else {
            intent.putExtra("showWarnBtn", false);
        }
        intent.putExtra("showDelBtn", false);
        intent.putExtra("showCopyLink", true);
        intent.putExtra("showShare", true);
        intent.putExtra("user", user);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_user), user.getUname(), user.getUid()));
        map.put("title", String.format(getString(R.string.share_user_title), user.getUname()));
        map.put("url", "http://bcy.net/u/" + user.getUid());
        if (!StringUtil.notNullEqual(user.getAvatar(), MyConstants.default_avatar)) {
            map.put("imagePath", user.getAvatar());
        }
        intent.putExtra("map", map);
        startActivityForResult(intent, ComplexDetailActivity.GOSHARE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }


    @Override
    public void onScroll(int Y) {
        mFoldLayout.changeHeader(Y);
        for (int i = 0; i < flist.size(); i++) {
            if (i != mPager.getCurrentItem()) {
                mFoldLayout.processTransY((FoldLayout.FoldChild) flist.get(i));
            }
        }
    }

    @Override
    public void onTop() {
        ll_header.setAlpha(1);
        findViewById(R.id.person_bg).setTranslationY(0);
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        try {
            switch (eventCode) {
                case BaseObserver.COMPELATE:
                    if (waitDialog.isShowing()) {
                        waitDialog.dismiss();
                    }
                    mProgressbarHelper.onSuccess();
                    break;
                case BaseObserver.START_LOADING:
                    waitDialog.show();
                    break;
                case BaseObserver.HIDE_BOTTOM:
                    hideBottom();
                    break;
                case BaseObserver.SHOW_BOTTOM:
                    showBottom();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_PIC) {
            try {
                String filepath = data.getExtras().getString("path");
                File tempfile = new File(ImageManager.getTemp(SmoothPersonActivity.this), "bcy_header_temp.jpg");
                File orginFile = new File(filepath);
                Uri tempUri = Uri.fromFile(tempfile);
                Uri orginUri = Uri.fromFile(orginFile);
                Crop.of(orginUri, tempUri).asSquare().start(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, data);
        } else if (requestCode == ComplexDetailActivity.GOSHARE) {
            if (resultCode == ShareActivity.BLOCK) {
                if (data != null) {
                    int is_block = data.getIntExtra("is_block", 0);
                    user.setIs_blocked(is_block);
                }
            }
        } else if (requestCode == GO_EDIT) {
            initData();
        }
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            handlePicResult(Crop.getOutput(result));
        } else if (resultCode == Crop.RESULT_ERROR) {
            MyToast.show(this, getString(R.string.not_support_type));
        }
    }

    public void handlePicResult(Uri uri) {
        if (uri == null) return;
        if (!NetUtils.checkNetwork(SmoothPersonActivity.this)) {
            MyToast.show(SmoothPersonActivity.this, getString(R.string.net_check_first));
            return;
        }
        mProgressDialog.show();
        Bitmap bm = BitmapFactory.decodeFile(uri.getPath());
        ImageManager.saveTempImage(SmoothPersonActivity.this, bm, PersonHelper.FAT, true, PersonHelper.FAT_SIZE, 100);
        ImageManager.saveTempImage(SmoothPersonActivity.this, bm, PersonHelper.BIG, true, PersonHelper.BIG_SIZE, 90);
        ImageManager.saveTempImage(SmoothPersonActivity.this, bm, PersonHelper.MIDDLE, true, PersonHelper.MIDDLE_SIZE, 90);
        ImageManager.saveTempImage(SmoothPersonActivity.this, bm, PersonHelper.SMALL, true, PersonHelper.SMALL_SIZE, 90);
        mHeadHelper.doPush();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
